import { textOption } from '../interface/shapes'

// 处理文字换行的绘制
export function _renderFont(
  ctx: any,
  {
    x,
    y,
    text,
    fontStyle,
    fontWeight,
    fontSize,
    width,
    height,
    stroke,
    textDecoration,
  }: textOption
) {
  x = 0
  y = 0
  let textData: any = {}
  //参数说明
  //ctx：canvas的 2d 对象，t：绘制的文字，x,y:文字坐标，s 文字的大小/行高,w：文字最大宽度 c文字颜色
  let chr = text.split('') // 把当前文字转化为数组
  let temp = '' // 当前用来做比较的字符串
  let row: string[] = [] // 最后分完行的文字数组
  let line = Math.floor(height / fontSize) // 判断有几行文字

  ctx.font = `${fontStyle} ${fontWeight} ${fontSize}px Arial`
  for (let a = 0; a < chr.length; a++) {
    let cur = ctx.measureText(temp)
    let next = ctx.measureText(temp + chr[a])
    console.log(cur.width, width, temp, 'curcurcur')

    if (!width || (cur.width < width && next.width <= width)) {
      temp += chr[a]
    } else {
      // 补充省略号
      if (line && line - 1 == row.length) {
        let lineArr = temp.split('')
        let index = lineArr.length
        // 省略号字符串需要占用的位置
        let ellipsis = ctx.measureText('...')
        // 需要删除的字符串
        let deleteStr = lineArr.reverse().reduce((cur, next) => {
          let text = cur + next
          let textAdd = ctx.measureText(text)
          if (textAdd.width > ellipsis.width) {
            return cur
          }
          return text
        }, '')
        lineArr.reverse()
        lineArr.splice(index - deleteStr.length, deleteStr.length, '...')
        let tempStr = lineArr.join('')
        row.push(tempStr)
        temp = ''
        break
      } else {
        row.push(temp)
        temp = chr[a]
      }
    }
  }
  row.push(temp)
  let textObj = ctx.measureText(row[row.length - 1])
  textData = {
    x,
    y,
    width: width || textObj.width,
    height: fontSize * row.length,
    lastWidth: textObj.width,
  }

  for (let b = 0; b < row.length; b++) {
    let sizeY = y + (b + 1) * (fontSize + b * 2)

    if (stroke.lineWidth != 0) {
      ctx.strokeText(row[b], x, sizeY)
    }
    ctx.fillText(row[b], x, sizeY) //每行字体y坐标间隔

    if (textDecoration == 'line-through') {
      ctx.fillRect(x, y + (b + 0.6) * fontSize, width || textData.lastWidth, 2)
    }
  }
  return textData
}
